package com.lagou.xm.io.sqlsession;

import com.lagou.xm.io.pojo.BoundSql;
import com.lagou.xm.io.pojo.Configuration;
import com.lagou.xm.io.pojo.MappedStatement;
import com.lagou.xm.io.utils.GenericTokenParser;
import com.lagou.xm.io.utils.ParameterMapping;
import com.lagou.xm.io.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    @Override
    public <E> E query(Configuration configuration, MappedStatement mappedStatement, Object... params) {
        try {
            // 获取数据库链接
            Connection connection = configuration.getDataSource().getConnection();
            // 转换sql
            BoundSql boundSql = getBoundSql(mappedStatement.getSql());
            // 设置执行sql
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
            // 获取参数的全类路径
            // 设置参数
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                // 参数实体类成员变量
                String content = parameterMapping.getContent();
                Field declaredField = mappedStatement.getParameterType().getDeclaredField(content);
                // 暴力获取私有成员变量值
                declaredField.setAccessible(true);
                preparedStatement.setObject(i + 1, declaredField.get(params[0]));
            }
            List<Object> result = new ArrayList<Object>();
            switch (mappedStatement.getSqlTypeEnum()) {
                case DELETE:
                case UPDATE:
                case INSERT:{
                    boolean execute = preparedStatement.execute();
                    result.add(execute);
                    break;
                }
                case SELECT:{
                    // 执行sql
                    ResultSet resultSet = preparedStatement.executeQuery();
                    while (resultSet.next()) {
                        Object o = mappedStatement.getResultType().newInstance();
                        ResultSetMetaData metaData = resultSet.getMetaData();
                        for (int i = 1; i <= metaData.getColumnCount(); i++) {
                            String columnName = metaData.getColumnName(i);
                            Object columnValue = resultSet.getObject(columnName);
                            // 内省
                            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, mappedStatement.getResultType());
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            writeMethod.invoke(o, columnValue);
                        }
                        result.add(o);
                    }
                    break;
                }
            }

            return (E) result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String resultSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(resultSql, parameterMappings);
    }
}
